# -*- coding:utf-8 -*-


from rest_framework.viewsets import ModelViewSet

from Apps.Interface.models.interface import Interface
from Apps.Interface.models.interfaceCat import InterfaceCat
from Apps.Interface.models.status import InterfaceStatus
from Apps.Interface.ser.interfaceSer import InterfaceSer
from Apps.Project.models.project import Project
from Apps.common.response import SuccessResponse
import json, logging

logger = logging.getLogger('django')


class InterfaceView(ModelViewSet):
    serializer_class = InterfaceSer
    queryset = Interface.objects.all()

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        serializer = self.get_serializer(queryset, many=True)
        return SuccessResponse(serializer.data)

    def create(self, request, *args, **kwargs):
        request.data["creator"] = request.user.id
        request.data["modifier"] = request.user.id

        request.data["project"] = Project.objects.filter(id=request.data["project"]).first().id

        if not request.data["interfaceCat"]:
            request.data["interfaceCat"] = None

        else:
            request.data["interface_category"] = InterfaceCat.objects.filter(id=request.data["interfaceCat"][-1]).first().id
        logger.info(request.data["interfaceCat"])
        request.data["interface_status"] = InterfaceStatus.objects.filter(status_code=1).first().id
        request.data["interface_cookie"] = json.dumps(request.data["interface_cookie"])
        request.data["interface_headers"] = json.dumps(request.data["interface_headers"])
        request.data["interface_params"] = json.dumps(request.data["interface_params"])
        request.data["interface_form"] = json.dumps(request.data["interface_cookie"])
        request.data["interface_cookie"] = json.dumps(request.data["interface_cookie"])
        request.data["interface_tags"] = json.dumps(request.data["interface_tags"])
        request.data["interface_setting"] = json.dumps(request.data["interface_setting"])

        # logger.info(request.data)

        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return SuccessResponse(serializer.data, headers=headers)

    def update(self, request, *args, **kwargs):
        request.data["modifier"] = request.user.id

        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        return SuccessResponse(serializer.data)

    def perform_update(self, serializer):
        serializer.save()

    def partial_update(self, request, *args, **kwargs):
        kwargs['partial'] = True
        return self.update(request, *args, **kwargs)
